#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    videoLocation=QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);

    display=new QLabel(this);
    display->setMinimumSize(MIN_SIZE);
    setCentralWidget(display);

    connect(&_timer,&QTimer::timeout,this,&MainWindow::nextFrame);
    move(200,100);
}

MainWindow::~MainWindow()
{
    if(capture.isOpened())
        capture.release();

    delete ui;
}

void MainWindow::on_actionOpen_triggered()
{
    QString path=QFileDialog::getOpenFileName(this,"选择视频文件",
                                              videoLocation,
                                              "视频文件 (*.mp4 *.mkv *.avi)");
    if(path.isEmpty())
        return;

    capture.open(path.toStdString());
    if(capture.isOpened())
    {
        double rate=capture.get(CAP_PROP_FPS);
        _timer.start(1000/rate);
        showVideoInfo();
    }
}

void MainWindow::nextFrame()
{
    Mat frame;
    capture >> frame;
    if(!frame.empty())
    {
        QImage image=cvMat_to_QImage(frame);
        QPixmap pix=QPixmap::fromImage(image);
        if(pix.width() > RES_720P.width())
            pix=pix.scaledToWidth(RES_720P.width());
        display->setPixmap(pix);
    }
}

void MainWindow::showVideoInfo()
{
    double rate=capture.get(CAP_PROP_FPS);
    double width=capture.get(CAP_PROP_FRAME_WIDTH);
    double height=capture.get(CAP_PROP_FRAME_HEIGHT);
    double frameCount=capture.get(CAP_PROP_FRAME_COUNT);

    QString info=
            QStringLiteral("帧率 ") + QString::number(rate) + QString(";")
            + QStringLiteral("帧宽 ") + QString::number(width) + QString(",")
            + QStringLiteral("帧高 ") + QString::number(height) + QString(";")
            + QStringLiteral("帧数 ") + QString::number(frameCount);

    ui->statusBar->showMessage(info);
}

